package queue

import (
	"fmt"
	"server/internal/svc"
	"strings"

	"github.com/zeromicro/go-queue/rabbitmq"
	"github.com/zeromicro/go-zero/core/service"
)

func Start(svc *svc.ServiceContext) []service.Service {
	c := svc.Config
	// fmt.Printf("queue at %v...\n", c.RabbitConf.ListenerQueues)
	conf := rabbitmq.RabbitConf{
		Username: c.RabbitConf.Username,
		Password: c.RabbitConf.Password,
		Host:     c.RabbitConf.Host,
		Port:     c.RabbitConf.Port,
		VHost:    c.RabbitConf.VHost,
	}
	listenerQueues := strings.SplitSeq(c.RabbitConf.ListenerQueues, ",")
	queueServers := make([]service.Service, 0)
	for name := range listenerQueues {
		if _, ok := Handlers[name]; !ok {
			fmt.Printf("[ERR] rabbitmq queue %s handle not found\n\n", name)
			continue
		}
		consumerConf := rabbitmq.ConsumerConf{
			Name:    name,
			AutoAck: false,
		}
		listener := MustNewListener(
			rabbitmq.RabbitListenerConf{
				RabbitConf:     conf,
				ListenerQueues: []rabbitmq.ConsumerConf{consumerConf},
			},
			Handlers[name],
			svc.Config,
		)

		fmt.Printf("Starting rabbitmq listener to %s...\n", name)
		// serviceGroup.Add(listener)
		queueServers = append(queueServers, listener)
	}
	return queueServers
}
